package org.jctc.els.modules.biz.controller.projects;

import cn.hutool.core.io.unit.DataSizeUtil;
import cn.hutool.core.util.IdUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.github.xiaoymin.knife4j.annotations.ApiOperationSupport;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import lombok.AllArgsConstructor;
import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
import org.jctc.els.common.config.BladeFileConfiguration;
import org.jctc.els.common.constant.BaseRoleConstant;
import org.jctc.els.modules.biz.entity.projects.ElsProjectFiles;
import org.jctc.els.modules.biz.entity.projects.ElsProjects;
import org.jctc.els.modules.biz.entity.projects.ElsProjectsStatusLog;
import org.jctc.els.modules.biz.excel.*;
import org.jctc.els.modules.biz.service.projects.ElsProjectFilesService;
import org.jctc.els.modules.biz.service.projects.ElsProjectsService;
import org.jctc.els.modules.biz.service.projects.ElsProjectsStatusLogService;
import org.jctc.els.modules.biz.vo.ElsProjectFilesVO;
import org.jctc.els.modules.biz.vo.ElsProjectTeamAuditVO;
import org.springblade.core.boot.ctrl.BladeController;
import org.springblade.core.cache.utils.CacheUtil;
import org.springblade.core.excel.util.ExcelUtil;
import org.springblade.core.log.annotation.ApiLog;
import org.springblade.core.mp.support.Condition;
import org.springblade.core.secure.BladeUser;
import org.springblade.core.secure.utils.AuthUtil;
import org.springblade.core.tenant.annotation.NonDS;
import org.springblade.core.tool.api.R;
import org.springblade.core.tool.utils.BaseRoleUtil;
import org.springblade.core.tool.utils.DateUtil;
import org.springblade.core.tool.utils.Func;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.commons.CommonsMultipartFile;
import springfox.documentation.annotations.ApiIgnore;

import javax.servlet.annotation.MultipartConfig;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.validation.Valid;
import java.io.File;
import java.util.*;

import static org.springblade.core.cache.constant.CacheConstant.PARAM_CACHE;

/**
 * 项目表;(els_projects)表控制层
 *
 * @author : Ice
 * @date : 2022-6-21
 */
@Api(tags = "项目表对象功能接口")
@RestController
@RequestMapping("/elsProjects")
@NonDS
@ApiIgnore
@AllArgsConstructor
@MultipartConfig
public class ElsProjectsController extends BladeController {

    @Autowired
    private ElsProjectsService elsProjectsService;

    @Autowired
    private ElsProjectFilesService elsProjectFilesService;

    private BladeFileConfiguration bladeFileConfiguration;

    @Autowired
    private ElsProjectsStatusLogService elsProjectsStatusLogService;

    /**
     * 通过ID查询单条数据
     *
     * @param id 主键
     * @return 实例对象
     */
    @ApiOperation("通过ID查询单条数据")
    @GetMapping("/detail")
    public ResponseEntity<ElsProjects> getById(@RequestParam("id") Long id) {
        ElsProjects byId = elsProjectsService.getById(id);
        return ResponseEntity.ok(byId);
    }

    /**
     * 分页查询
     *
     * @param pageNum
     * @param pageSize
     * @return 查询结果
     */
    @ApiOperation("分页查询")
    @GetMapping("/page")
    public R<IPage<ElsProjects>> paginQuery(@RequestParam(value = "pageNum") Integer pageNum,
                                            @RequestParam(value = "pageSize") Integer pageSize,
                                            @RequestParam(value = "projectName") String projectName) {
        IPage<ElsProjects> elsProjectsPage = elsProjectsService.paginQuery(pageNum, pageSize,projectName);
        return R.data(elsProjectsPage);
    }

    @ApiOperation("分页查询")
    @GetMapping("/team-audit")
    public R<IPage<ElsProjectTeamAuditVO>> paginQueryTeamAudit(@RequestParam(value = "pageNum") Integer pageNum,
                                                               @RequestParam(value = "pageSize") Integer pageSize,
                                                               @RequestParam(value = "projectCategory", required = false) Integer projectCategory,
                                                               @RequestParam(value = "projectName") String projectName,@RequestParam(value = "teamId") Long teamId,
                                                               @RequestParam(value = "status")Integer status) {
        Long userId = AuthUtil.getUserId();
        IPage<ElsProjectTeamAuditVO> elsProjectsPage = elsProjectsService.paginQueryTeamAudit(pageNum, pageSize,projectName,userId,projectCategory,teamId,status);
        return R.data(elsProjectsPage);
    }

    @ApiOperation("分页查询")
    @GetMapping("/admin-audit")
    public R<IPage<ElsProjectTeamAuditVO>> paginQueryAdminAudit(@RequestParam(value = "pageNum") Integer pageNum,
                                                               @RequestParam(value = "pageSize") Integer pageSize,
                                                               @RequestParam(value = "projectCategory", required = false) Integer projectCategory,
                                                               @RequestParam(value = "projectName") String projectName,
                                                               @RequestParam(value = "teamId",required = false) Long teamId,
                                                               @RequestParam(value = "status") Integer status
    ) {
        Long userId = AuthUtil.getUserId();
        IPage<ElsProjectTeamAuditVO> elsProjectsPage = elsProjectsService.paginQueryAdminAudit(pageNum, pageSize,projectName,userId,projectCategory,teamId,status);
        return R.data(elsProjectsPage);
    }

    @GetMapping("/category-page")
    public R<IPage<ElsProjectFilesVO>> paginCategoryQuery(@RequestParam(value = "pageNum") Integer pageNum,
                                                    @RequestParam(value = "pageSize") Integer pageSize,
                                                    @RequestParam(value = "projectCategory", required = false) Integer projectCategory,
                                                    @RequestParam(value = "projectType") Integer projectType,
                                                    @RequestParam(value = "projectName") String projectName) {
        Long baseRole = AuthUtil.getBaseRole();
        IPage<ElsProjectFilesVO> elsProjectsPage = null;
        //专家查询自己可以评分的项目
        if(BaseRoleUtil.hasRole(baseRole,BaseRoleConstant.BASE_EXPERT_ROLE)){
            elsProjectsPage = elsProjectsService.paginCategoryQueryByExpert(pageNum, pageSize,projectCategory,projectType,projectName,AuthUtil.getUserId());
        }else if(BaseRoleUtil.hasRole(baseRole,BaseRoleConstant.BASE_SPECIAL_ROLE)){
            //地市专责只能看到自己创建的项目
            elsProjectsPage = elsProjectsService.paginCategoryQueryBySpecial(pageNum, pageSize,projectCategory,projectType,projectName,AuthUtil.getUserId());
        }else if(BaseRoleUtil.hasRole(baseRole,BaseRoleConstant.BASE_SPECIAL_ADMIN_ROLE)){
            //地市管理员只能看到下属地市专责提交的项目
            elsProjectsPage = elsProjectsService.paginCategoryQueryByDeptId(pageNum, pageSize,projectCategory,projectType,projectName,AuthUtil.getDeptId());
        }else {
            //管理员查询全部项目
            elsProjectsPage = elsProjectsService.paginCategoryQuery(pageNum, pageSize,projectCategory,projectType,projectName);
        }
        return R.data(elsProjectsPage);
    }

    /**
     * 新增数据
     *
     * @param elsProjects 实例对象
     * @return 实例对象
     */
    @ApiOperation("新增数据")
    @PostMapping("/save")
    public R add(@Valid @RequestBody ElsProjectFilesVO elsProjects) {

        ElsProjects projects = Func.copy(elsProjects, ElsProjects.class);
        Calendar calendar = Calendar.getInstance();
        projects.setYear(calendar.get(Calendar.YEAR));
        projects.setIsFallbackt(0);
        Long baseRole = AuthUtil.getBaseRole();
        if (BaseRoleUtil.hasRole(baseRole, BaseRoleConstant.BASE_SPECIAL_ROLE)) {
            projects.setAuditStatus(0);
        } else if (BaseRoleUtil.hasRole(baseRole, BaseRoleConstant.BASE_SPECIAL_ADMIN_ROLE)) {
            projects.setAuditStatus(2);
        } else {
            projects.setAuditStatus(4);
        }
        projects.setDeptId(Long.parseLong(AuthUtil.getDeptId()));
        boolean insert = elsProjectsService.save(projects);
        if (insert) {
            Long projectsId = projects.getId();
            for (ElsProjectFiles elsProjectFiles : elsProjects.getFileNames()) {
                ElsProjectFiles projectFiles = new ElsProjectFiles();
                projectFiles.setProjectId(projectsId);
                projectFiles.setFileType(elsProjectFiles.getFileType());
                projectFiles.setFileName(elsProjectFiles.getFileName());
                projectFiles.setPath(elsProjectFiles.getFileName());
                projectFiles.setFileSuffix(elsProjectFiles.getFileSuffix());
                elsProjectFilesService.save(projectFiles);
            }
        }
        return R.data(insert);
    }

    /**
     * 更新数据
     *
     * @param elsProjects 实例对象
     * @return 实例对象
     */
    @ApiOperation("更新数据")
    @PutMapping("/update")
    public ResponseEntity edit(@Valid @RequestBody  ElsProjectFilesVO elsProjects) {

        ElsProjects projects = Func.copy(elsProjects, ElsProjects.class);
        Calendar calendar = Calendar.getInstance();
        projects.setYear(calendar.get(Calendar.YEAR));
        boolean update = elsProjectsService.updateById(elsProjects);
        if (update) {
            Long projectsId = projects.getId();
            for (ElsProjectFiles elsProjectFiles : elsProjects.getFileNames()) {
                Long id = elsProjectFiles.getId();
                if (id==null){
                    ElsProjectFiles projectFiles = new ElsProjectFiles();
                    projectFiles.setProjectId(projectsId);
                    projectFiles.setFileType(elsProjectFiles.getFileType());
                    projectFiles.setFileName(elsProjectFiles.getFileName());
                    projectFiles.setPath(elsProjectFiles.getFileName());
                    projectFiles.setFileSuffix(elsProjectFiles.getFileSuffix());
                    elsProjectFilesService.save(projectFiles);
                }
                elsProjectFilesService.updateById(elsProjectFiles);
            }
        }
        return ResponseEntity.ok(update);
    }

    @ApiOperation("提交项目")
    @PutMapping("/submit")
    public ResponseEntity submit(@Valid @RequestBody  ElsProjects elsProjects) {
        elsProjects.setIsFallbackt(0);
        boolean update = elsProjectsService.updateById(elsProjects);
        return ResponseEntity.ok(update);
    }

    @ApiOperation("提交下一级审核")
    @PutMapping("/submit/audit")
    @Transactional(rollbackFor = Exception.class)
    public ResponseEntity submitAudit(@Valid @RequestBody  ElsProjects elsProjects) {
        Long baseRole = AuthUtil.getBaseRole();
        if (BaseRoleUtil.hasRole(baseRole, BaseRoleConstant.BASE_SPECIAL_ROLE)) {
            elsProjects.setAuditStatus(1);
            ElsProjectsStatusLog elsProjectsStatusLog = new ElsProjectsStatusLog();
            elsProjectsStatusLog.setProjectId(elsProjects.getId());
            elsProjectsStatusLog.setStatus(2);
            elsProjectsStatusLog.setAuthTime(DateUtil.now());
            elsProjectsStatusLog.setAuthBy(AuthUtil.getUserId());
            elsProjectsStatusLog.setBaseRole(baseRole);
            elsProjectsStatusLog.setAuthDesc("提交项目");
            elsProjectsStatusLog.setDeptId(Long.parseLong(AuthUtil.getDeptId()));
            elsProjectsStatusLog.setCreatedBy(AuthUtil.getUserId().toString());
            elsProjectsStatusLog.setCreatedTime(DateUtil.now());
            elsProjectsStatusLog.setUpdatedBy(AuthUtil.getUserId().toString());
            elsProjectsStatusLog.setUpdatedTime(DateUtil.now());
            elsProjectsStatusLogService.save(elsProjectsStatusLog);
        } else if (BaseRoleUtil.hasRole(baseRole, BaseRoleConstant.BASE_SPECIAL_ADMIN_ROLE)) {
            elsProjects.setAuditStatus(3);
            ElsProjectsStatusLog elsProjectsStatusLog = new ElsProjectsStatusLog();
            elsProjectsStatusLog.setProjectId(elsProjects.getId());
            elsProjectsStatusLog.setStatus(2);
            elsProjectsStatusLog.setAuthTime(DateUtil.now());
            elsProjectsStatusLog.setAuthBy(AuthUtil.getUserId());
            elsProjectsStatusLog.setBaseRole(baseRole);
            elsProjectsStatusLog.setAuthDesc("提交项目");
            elsProjectsStatusLog.setDeptId(Long.parseLong(AuthUtil.getDeptId()));
            elsProjectsStatusLog.setCreatedBy(AuthUtil.getUserId().toString());
            elsProjectsStatusLog.setCreatedTime(DateUtil.now());
            elsProjectsStatusLog.setUpdatedBy(AuthUtil.getUserId().toString());
            elsProjectsStatusLog.setUpdatedTime(DateUtil.now());
            elsProjectsStatusLogService.save(elsProjectsStatusLog);
        } else if (BaseRoleUtil.hasRole(baseRole,BaseRoleConstant.BASE_EXPERT_ROLE)) {
            elsProjects.setAuditStatus(5);
            ElsProjectsStatusLog elsProjectsStatusLog = new ElsProjectsStatusLog();
            elsProjectsStatusLog.setProjectId(elsProjects.getId());
            elsProjectsStatusLog.setStatus(2);
            elsProjectsStatusLog.setAuthTime(DateUtil.now());
            elsProjectsStatusLog.setAuthBy(AuthUtil.getUserId());
            elsProjectsStatusLog.setBaseRole(baseRole);
            elsProjectsStatusLog.setAuthDesc("提交项目");
            elsProjectsStatusLog.setDeptId(Long.parseLong(AuthUtil.getDeptId()));
            elsProjectsStatusLog.setCreatedBy(AuthUtil.getUserId().toString());
            elsProjectsStatusLog.setCreatedTime(DateUtil.now());
            elsProjectsStatusLog.setUpdatedBy(AuthUtil.getUserId().toString());
            elsProjectsStatusLog.setUpdatedTime(DateUtil.now());
            elsProjectsStatusLogService.save(elsProjectsStatusLog);
        }
        boolean update = elsProjectsService.updateById(elsProjects);
        return ResponseEntity.ok(update);
    }

    @ApiOperation("项目审核")
    @PutMapping("/audit")
    @Transactional(rollbackFor = Exception.class)
    public ResponseEntity audit(@Valid @RequestBody  ElsProjectsStatusLog elsProjectsStatusLog) {
        Long baseRole = AuthUtil.getBaseRole();
        ElsProjects projects = new ElsProjects();
        projects.setId(elsProjectsStatusLog.getProjectId());
        if (elsProjectsStatusLog.getStatus() == 1) {
            if (BaseRoleUtil.hasRole(baseRole, BaseRoleConstant.BASE_SPECIAL_ADMIN_ROLE)) {
                projects.setAuditStatus(2);
            } else if (BaseRoleUtil.hasRole(baseRole, BaseRoleConstant.BASE_ADMIN_ROLE)) {
                projects.setAuditStatus(4);
            }  else if (BaseRoleUtil.hasRole(baseRole, BaseRoleConstant.BASE_EXPERT_ROLE)) {
                projects.setAuditStatus(5);
            }
            elsProjectsStatusLog.setAuthTime(DateUtil.now());
            elsProjectsStatusLog.setAuthBy(AuthUtil.getUserId());
            elsProjectsStatusLog.setBaseRole(baseRole);
            elsProjectsStatusLog.setDeptId(Long.parseLong(AuthUtil.getDeptId()));
            elsProjectsStatusLog.setCreatedBy(AuthUtil.getUserId().toString());
            elsProjectsStatusLog.setCreatedTime(DateUtil.now());
            elsProjectsStatusLog.setUpdatedBy(AuthUtil.getUserId().toString());
            elsProjectsStatusLog.setUpdatedTime(DateUtil.now());
            elsProjectsStatusLogService.save(elsProjectsStatusLog);
        } else {
            projects.setAuditStatus(0);
            elsProjectsStatusLog.setAuthTime(DateUtil.now());
            elsProjectsStatusLog.setAuthBy(AuthUtil.getUserId());
            elsProjectsStatusLog.setBaseRole(baseRole);
            elsProjectsStatusLog.setDeptId(Long.parseLong(AuthUtil.getDeptId()));
            elsProjectsStatusLog.setCreatedBy(AuthUtil.getUserId().toString());
            elsProjectsStatusLog.setCreatedTime(DateUtil.now());
            elsProjectsStatusLog.setUpdatedBy(AuthUtil.getUserId().toString());
            elsProjectsStatusLog.setUpdatedTime(DateUtil.now());
            elsProjectsStatusLogService.save(elsProjectsStatusLog);
        }
        boolean b = elsProjectsService.updateById(projects);
        return ResponseEntity.ok(b);
    }

    @ApiOperation("回退")
    @PutMapping("/fallbackt")
    public ResponseEntity fallbackt(@Valid @RequestBody  ElsProjects elsProjects) {
        elsProjects.setIsFallbackt(-1);
        boolean update = elsProjectsService.updateById(elsProjects);
        return ResponseEntity.ok(update);
    }

    /**
     * 通过主键删除数据
     *
     * @param ids 主键
     * @return 是否成功
     */
    @ApiOperation("通过主键删除数据")
    @DeleteMapping("/remove")
    public R deleteById(@ApiParam(value = "主键集合", required = true) @RequestParam String ids) {
        boolean delete = elsProjectsService.removes(Func.toLongList(ids));
        return R.status(delete);
    }

    @DeleteMapping("/delete")
    @ApiOperation(value = "逻辑删除", notes = "传入ids")
    public R remove(@ApiParam(value = "主键集合", required = true) @RequestParam String ids) {

        return R.status(elsProjectsService.deleteLogic(Func.toLongList(ids)));
    }

    /**
     * 导入职工培训项目
     */
    @PostMapping("import-projects-workers")
    @ApiOperation(value = "导入职工培训项目", notes = "传入excel")
    public R importWorkersProjects(HttpServletRequest request,Integer projectCategory,Integer projectType) {
        String fileName = "";
        //创建一个“硬盘文件条目工厂”对象
        DiskFileItemFactory factory = new DiskFileItemFactory();
        //设置阈值，设置JVM一次能够处理的文件大小（默认吞吐量是10KB）
        factory.setSizeThreshold(DiskFileItemFactory.DEFAULT_SIZE_THRESHOLD);
        //设置临时文件的存储位置（文件大小大于吞吐量的话就必须设置这个值，比如文件大小：1GB ，一次吞吐量：1MB）
        factory.setRepository(new File(bladeFileConfiguration.getUploadPath()));
        //创建核心对象
        ServletFileUpload fileUpload = new ServletFileUpload(factory);
        //设置最大可支持的文件大小（10MB）
        fileUpload.setFileSizeMax(1024 * 1024 * 50);
        //设置转换时使用的字符集
        fileUpload.setHeaderEncoding("UTF-8");
        if (ServletFileUpload.isMultipartContent(request)) {
            try {
                List<FileItem> fileItems = fileUpload.parseRequest(request);
                for (FileItem fileItem : fileItems) {
                    if (fileItem.isFormField()) {//判断该FileItem为一个普通的form元素
                        //获取字段名
                        String fieldName = fileItem.getFieldName();
                        //获取字段值，并解决乱码
                        String fieldValue = fileItem.getString("UTF-8");
                        System.out.println(fieldName + " : " + fieldValue);

                    } else {//判断该FileItem为一个文件

                        System.out.println("Start to upload file!");
                        //获取文件名
                        fileName = fileItem.getName();
                        System.out.println("fileName : " + fileName);
                        //获取文件大小
                        long fileSize = fileItem.getSize();
                        MultipartFile multipartFile = new CommonsMultipartFile(fileItem);
                        BladeUser user = getUser();
                        return elsProjectsService.importWorkersProjects(multipartFile, request,projectCategory,projectType,user);
                        //fileItem.write(new File(bladeFileConfiguration.getUploadPath() + File.separator + fileName));
                    }
                }
            } catch (Exception e) {
                e.printStackTrace();
                return R.fail(e.getMessage());
            }
        }
        return R.success("导入成功");
    }

    /**
     * 导入人才评价培训项目
     */
    @PostMapping("import-projects-personnel")
    @ApiOperation(value = "导入人才评价培训项目", notes = "传入excel")
    public R importPersonnelProjects(HttpServletRequest request,Integer projectCategory,Integer projectType) {
        String fileName = "";
        //创建一个“硬盘文件条目工厂”对象
        DiskFileItemFactory factory = new DiskFileItemFactory();
        //设置阈值，设置JVM一次能够处理的文件大小（默认吞吐量是10KB）
        factory.setSizeThreshold(DiskFileItemFactory.DEFAULT_SIZE_THRESHOLD);
        //设置临时文件的存储位置（文件大小大于吞吐量的话就必须设置这个值，比如文件大小：1GB ，一次吞吐量：1MB）
        factory.setRepository(new File(bladeFileConfiguration.getUploadPath()));
        //创建核心对象
        ServletFileUpload fileUpload = new ServletFileUpload(factory);
        //设置最大可支持的文件大小（10MB）
        fileUpload.setFileSizeMax(1024 * 1024 * 50);
        //设置转换时使用的字符集
        fileUpload.setHeaderEncoding("UTF-8");
        if (ServletFileUpload.isMultipartContent(request)) {
            try {
                List<FileItem> fileItems = fileUpload.parseRequest(request);
                for (FileItem fileItem : fileItems) {
                    if (fileItem.isFormField()) {//判断该FileItem为一个普通的form元素
                        //获取字段名
                        String fieldName = fileItem.getFieldName();
                        //获取字段值，并解决乱码
                        String fieldValue = fileItem.getString("UTF-8");
                        System.out.println(fieldName + " : " + fieldValue);

                    } else {//判断该FileItem为一个文件

                        System.out.println("Start to upload file!");
                        //获取文件名
                        fileName = fileItem.getName();
                        System.out.println("fileName : " + fileName);
                        //获取文件大小
                        long fileSize = fileItem.getSize();
                        MultipartFile multipartFile = new CommonsMultipartFile(fileItem);
                        BladeUser user = getUser();
                        return elsProjectsService.importPersonnelProjects(multipartFile, request,projectCategory,projectType,user);
                        //fileItem.write(new File(bladeFileConfiguration.getUploadPath() + File.separator + fileName));
                    }
                }
            } catch (Exception e) {
                e.printStackTrace();
                return R.fail(e.getMessage());
            }
        }
        return R.success("导入成功");
    }

    /**
     * 导入培训开发项目
     */
    @PostMapping("import-projects-exploit")
    @ApiOperation(value = "导入培训开发项目", notes = "传入excel")
    public R importExploitProjects(HttpServletRequest request,Integer projectCategory,Integer projectType) {
        boolean result = false;
        String fileName = "";
        //创建一个“硬盘文件条目工厂”对象
        DiskFileItemFactory factory = new DiskFileItemFactory();
        //设置阈值，设置JVM一次能够处理的文件大小（默认吞吐量是10KB）
        factory.setSizeThreshold(DiskFileItemFactory.DEFAULT_SIZE_THRESHOLD);
        //设置临时文件的存储位置（文件大小大于吞吐量的话就必须设置这个值，比如文件大小：1GB ，一次吞吐量：1MB）
        factory.setRepository(new File(bladeFileConfiguration.getUploadPath()));
        //创建核心对象
        ServletFileUpload fileUpload = new ServletFileUpload(factory);
        //设置最大可支持的文件大小（10MB）
        fileUpload.setFileSizeMax(1024 * 1024 * 50);
        //设置转换时使用的字符集
        fileUpload.setHeaderEncoding("UTF-8");
        if (ServletFileUpload.isMultipartContent(request)) {
            try {
                List<FileItem> fileItems = fileUpload.parseRequest(request);
                for (FileItem fileItem : fileItems) {
                    if (fileItem.isFormField()) {//判断该FileItem为一个普通的form元素
                        //获取字段名
                        String fieldName = fileItem.getFieldName();
                        //获取字段值，并解决乱码
                        String fieldValue = fileItem.getString("UTF-8");
                        System.out.println(fieldName + " : " + fieldValue);

                    } else {//判断该FileItem为一个文件

                        System.out.println("Start to upload file!");
                        //获取文件名
                        fileName = fileItem.getName();
                        System.out.println("fileName : " + fileName);
                        //获取文件大小
                        long fileSize = fileItem.getSize();
                        MultipartFile multipartFile = new CommonsMultipartFile(fileItem);
                        BladeUser user = getUser();
                        return elsProjectsService.importExploitProjects(multipartFile, request,projectCategory,projectType,user);
                        //fileItem.write(new File(bladeFileConfiguration.getUploadPath() + File.separator + fileName));
                    }
                }
            } catch (Exception e) {
                e.printStackTrace();
                return R.fail(e.getMessage());
            }
        }
        return R.success("导入成功");
    }


    /**
     * 导入培训购置项目
     */
    @PostMapping("import-projects-purchase")
    @ApiOperation(value = "导入培训购置项目", notes = "传入excel")
    public R importPurchaseProjects(HttpServletRequest request,Integer projectCategory,Integer projectType) {
        String fileName = "";
        //创建一个“硬盘文件条目工厂”对象
        DiskFileItemFactory factory = new DiskFileItemFactory();
        //设置阈值，设置JVM一次能够处理的文件大小（默认吞吐量是10KB）
        factory.setSizeThreshold(DiskFileItemFactory.DEFAULT_SIZE_THRESHOLD);
        //设置临时文件的存储位置（文件大小大于吞吐量的话就必须设置这个值，比如文件大小：1GB ，一次吞吐量：1MB）
        factory.setRepository(new File(bladeFileConfiguration.getUploadPath()));
        //创建核心对象
        ServletFileUpload fileUpload = new ServletFileUpload(factory);
        //设置最大可支持的文件大小（10MB）
        fileUpload.setFileSizeMax(1024 * 1024 * 50);
        //设置转换时使用的字符集
        fileUpload.setHeaderEncoding("UTF-8");
        if (ServletFileUpload.isMultipartContent(request)) {
            try {
                List<FileItem> fileItems = fileUpload.parseRequest(request);
                for (FileItem fileItem : fileItems) {
                    if (fileItem.isFormField()) {//判断该FileItem为一个普通的form元素
                        //获取字段名
                        String fieldName = fileItem.getFieldName();
                        //获取字段值，并解决乱码
                        String fieldValue = fileItem.getString("UTF-8");
                        System.out.println(fieldName + " : " + fieldValue);

                    } else {//判断该FileItem为一个文件

                        System.out.println("Start to upload file!");
                        //获取文件名
                        fileName = fileItem.getName();
                        System.out.println("fileName : " + fileName);
                        //获取文件大小
                        long fileSize = fileItem.getSize();
                        MultipartFile multipartFile = new CommonsMultipartFile(fileItem);
                        BladeUser user = getUser();
                        return elsProjectsService.importPurchaseProjects(multipartFile, request,projectCategory,projectType,user);
                        //fileItem.write(new File(bladeFileConfiguration.getUploadPath() + File.separator + fileName));
                    }
                }
            } catch (Exception e) {
                e.printStackTrace();
                return R.fail(e.getMessage());
            }
        }
        return R.success("导入成功");
    }

    /**
     * 导入生产辅助技改(大修)项目
     */
    @PostMapping("import-projects-produce")
    @ApiOperation(value = "导入生产辅助技改(大修)项目", notes = "传入excel")
    public R importProduceProjects(HttpServletRequest request,Integer projectCategory,Integer projectType) {
        String fileName = "";
        //创建一个“硬盘文件条目工厂”对象
        DiskFileItemFactory factory = new DiskFileItemFactory();
        //设置阈值，设置JVM一次能够处理的文件大小（默认吞吐量是10KB）
        factory.setSizeThreshold(DiskFileItemFactory.DEFAULT_SIZE_THRESHOLD);
        //设置临时文件的存储位置（文件大小大于吞吐量的话就必须设置这个值，比如文件大小：1GB ，一次吞吐量：1MB）
        factory.setRepository(new File(bladeFileConfiguration.getUploadPath()));
        //创建核心对象
        ServletFileUpload fileUpload = new ServletFileUpload(factory);
        //设置最大可支持的文件大小（10MB）
        fileUpload.setFileSizeMax(1024 * 1024 * 50);
        //设置转换时使用的字符集
        fileUpload.setHeaderEncoding("UTF-8");
        if (ServletFileUpload.isMultipartContent(request)) {
            try {
                List<FileItem> fileItems = fileUpload.parseRequest(request);
                for (FileItem fileItem : fileItems) {
                    if (fileItem.isFormField()) {//判断该FileItem为一个普通的form元素
                        //获取字段名
                        String fieldName = fileItem.getFieldName();
                        //获取字段值，并解决乱码
                        String fieldValue = fileItem.getString("UTF-8");
                        System.out.println(fieldName + " : " + fieldValue);

                    } else {//判断该FileItem为一个文件

                        System.out.println("Start to upload file!");
                        //获取文件名
                        fileName = fileItem.getName();
                        System.out.println("fileName : " + fileName);
                        //获取文件大小
                        long fileSize = fileItem.getSize();
                        MultipartFile multipartFile = new CommonsMultipartFile(fileItem);
                        BladeUser user = getUser();
                        return elsProjectsService.importProduceProjects(multipartFile, request,projectCategory,projectType,user);
                        //fileItem.write(new File(bladeFileConfiguration.getUploadPath() + File.separator + fileName));
                    }
                }
            } catch (Exception e) {
                e.printStackTrace();
                return R.fail(e.getMessage());
            }
        }
        return R.success("导入成功");
    }

    /**
     * 导入材料评审项目
     */
    @PostMapping("import-projects-science")
    @ApiOperation(value = "导出材料评审项目")
    public R exportProjectsScience(HttpServletRequest request,Integer projectType){
        String fileName = "";
        //创建一个“硬盘文件条目工厂”对象
        DiskFileItemFactory factory = new DiskFileItemFactory();
        //设置阈值，设置JVM一次能够处理的文件大小（默认吞吐量是10KB）
        factory.setSizeThreshold(DiskFileItemFactory.DEFAULT_SIZE_THRESHOLD);
        //设置临时文件的存储位置（文件大小大于吞吐量的话就必须设置这个值，比如文件大小：1GB ，一次吞吐量：1MB）
        factory.setRepository(new File(bladeFileConfiguration.getUploadPath()));
        //创建核心对象
        ServletFileUpload fileUpload = new ServletFileUpload(factory);
        //设置最大可支持的文件大小（10MB）
        fileUpload.setFileSizeMax(1024 * 1024 * 50);
        //设置转换时使用的字符集
        fileUpload.setHeaderEncoding("UTF-8");
        if (ServletFileUpload.isMultipartContent(request)) {
            try {
                List<FileItem> fileItems = fileUpload.parseRequest(request);
                for (FileItem fileItem : fileItems) {
                    if (fileItem.isFormField()) {//判断该FileItem为一个普通的form元素
                        //获取字段名
                        String fieldName = fileItem.getFieldName();
                        //获取字段值，并解决乱码
                        String fieldValue = fileItem.getString("UTF-8");
                        System.out.println(fieldName + " : " + fieldValue);

                    } else {//判断该FileItem为一个文件

                        System.out.println("Start to upload file!");
                        //获取文件名
                        fileName = fileItem.getName();
                        System.out.println("fileName : " + fileName);
                        //获取文件大小
                        long fileSize = fileItem.getSize();
                        MultipartFile multipartFile = new CommonsMultipartFile(fileItem);
                        return elsProjectsService.importScienceProjects(multipartFile, request,projectType);
                        //fileItem.write(new File(bladeFileConfiguration.getUploadPath() + File.separator + fileName));
                    }
                }
            } catch (Exception e) {
                e.printStackTrace();
                return R.fail(e.getMessage());
            }
        }
        return R.success("导入成功");
    }

    /**
     * 导出职工培训项目
     */
    @GetMapping("export-projects-personnel")
    @ApiOperation(value = "导出人才评价培训项目")
    public void exportPersonnelProjects(@ApiIgnore @RequestParam Map<String, Object> projects, HttpServletResponse response,Integer projectCategory,Integer projectType,String projectName) {
        QueryWrapper<ElsProjects> queryWrapper = Condition.getQueryWrapper(projects, ElsProjects.class);
        Long baseRole = AuthUtil.getBaseRole();
        List<PersonnelProjectsExcel> list = null;
        //专家导出自己可以评分的项目
//        if(BaseRoleUtil.hasRole(baseRole,BaseRoleConstant.BASE_EXPERT_ROLE)) {
//            list = elsProjectsService.exportPersonnelProjects(queryWrapper, projectCategory, projectType, AuthUtil.getUserId());
//        }else{
//            list = elsProjectsService.exportPersonnelProjects(queryWrapper, projectCategory, projectType, null);
//        }
        //专家查询自己可以评分的项目
        if(BaseRoleUtil.hasRole(baseRole,BaseRoleConstant.BASE_EXPERT_ROLE)){
            list = elsProjectsService.paginCategoryQueryByExpertExcelPersonnel(projectCategory,projectType,projectName,AuthUtil.getUserId());
        }else if(BaseRoleUtil.hasRole(baseRole,BaseRoleConstant.BASE_SPECIAL_ROLE)){
            //地市专责只能看到自己创建的项目
            list = elsProjectsService.paginCategoryQueryBySpecialExcelPersonnel(projectCategory,projectType,projectName,AuthUtil.getUserId());
        }else {
            //管理员查询全部项目
            list = elsProjectsService.paginCategoryQueryExcelPersonnel(projectCategory,projectType,projectName);
        }
        ExcelUtil.export(response, "人才评价培训项目数据" + DateUtil.time(), "人才评价培训项目数据表", list, PersonnelProjectsExcel.class);
    }
    /**
     * 导出培训开发项目
     */
    @GetMapping("export-projects-exploit")
    @ApiOperation(value = "导出培训开发项目")
    public void exportExploitProjects(@ApiIgnore @RequestParam Map<String, Object> projects, HttpServletResponse response,Integer projectCategory,Integer projectType,String projectName) {
        QueryWrapper<ElsProjects> queryWrapper = Condition.getQueryWrapper(projects, ElsProjects.class);
        Long baseRole = AuthUtil.getBaseRole();
        List<ExploitProjectsExcel> list = null;
        //专家导出自己可以评分的项目
        if(BaseRoleUtil.hasRole(baseRole,BaseRoleConstant.BASE_EXPERT_ROLE)){
            list = elsProjectsService.paginCategoryQueryByExpertExcelExploit(projectCategory,projectType,projectName,AuthUtil.getUserId());
        }else if(BaseRoleUtil.hasRole(baseRole,BaseRoleConstant.BASE_SPECIAL_ROLE)){
            //地市专责只能看到自己创建的项目
            list = elsProjectsService.paginCategoryQueryBySpecialExcelExploit(projectCategory,projectType,projectName,AuthUtil.getUserId());
        }else {
            //管理员查询全部项目
            list = elsProjectsService.paginCategoryQueryExcelExploit(projectCategory,projectType,projectName);
        }
        ExcelUtil.export(response, "培训开发项目数据" + DateUtil.time(), "培训开发项目数据表", list, ExploitProjectsExcel.class);
    }
    /**
     * 导出培训购置项目
     */
    @GetMapping("export-projects-purchase")
    @ApiOperation(value = "导出培训购置项目")
    public void exportPurchaseProjects(@ApiIgnore @RequestParam Map<String, Object> projects, HttpServletResponse response,Integer projectCategory,Integer projectType,String projectName) {
        QueryWrapper<ElsProjects> queryWrapper = Condition.getQueryWrapper(projects, ElsProjects.class);
        Long baseRole = AuthUtil.getBaseRole();
        List<PurchaseProjectExcel> list =null;
        //专家导出自己可以评分的项目
        if(BaseRoleUtil.hasRole(baseRole,BaseRoleConstant.BASE_EXPERT_ROLE)){
            list = elsProjectsService.paginCategoryQueryByExpertExcelPurchase(projectCategory,projectType,projectName,AuthUtil.getUserId());
        }else if(BaseRoleUtil.hasRole(baseRole,BaseRoleConstant.BASE_SPECIAL_ROLE)){
            //地市专责只能看到自己创建的项目
            list = elsProjectsService.paginCategoryQueryBySpecialExcelPurchase(projectCategory,projectType,projectName,AuthUtil.getUserId());
        }else {
            //管理员查询全部项目
            list = elsProjectsService.paginCategoryQueryExcelPurchase(projectCategory,projectType,projectName);
        }
        ExcelUtil.export(response, "培训购置项目数据" + DateUtil.time(), "培训购置项目数据表", list, PurchaseProjectExcel.class);
    }
    /**
     * 导出生产辅助技改(大修)项目
     */
    @GetMapping("export-projects-produce")
    @ApiOperation(value = "导出生产辅助技改(大修)项目")
    public void exportProduceProjects(@ApiIgnore @RequestParam Map<String, Object> projects, HttpServletResponse response,Integer projectCategory,Integer projectType,String projectName) {
        QueryWrapper<ElsProjects> queryWrapper = Condition.getQueryWrapper(projects, ElsProjects.class);
        Long baseRole = AuthUtil.getBaseRole();
        List<ProduceProjectsExcel> list = null;
        //专家导出自己可以评分的项目
        if(BaseRoleUtil.hasRole(baseRole,BaseRoleConstant.BASE_EXPERT_ROLE)){
            list = elsProjectsService.paginCategoryQueryByExpertExcelProject(projectCategory,projectType,projectName,AuthUtil.getUserId());
        }else if(BaseRoleUtil.hasRole(baseRole,BaseRoleConstant.BASE_SPECIAL_ROLE)){
            //地市专责只能看到自己创建的项目
            list = elsProjectsService.paginCategoryQueryBySpecialExcelProject(projectCategory,projectType,projectName,AuthUtil.getUserId());
        }else {
            //管理员查询全部项目
            list = elsProjectsService.paginCategoryQueryExcelProject(projectCategory,projectType,projectName);
        }
        ExcelUtil.export(response, "生产辅助技改(大修)项目数据" + DateUtil.time(), "生产辅助技改(大修)项目数据表", list, ProduceProjectsExcel.class);
    }
    /**
     * 导出材料评审项目
     */
    @GetMapping("export-projects-science")
    @ApiOperation(value = "导出材料评审项目")
    public void exportProduceScience(@ApiIgnore @RequestParam Map<String, Object> projects, HttpServletResponse response,Integer projectType) {
        QueryWrapper<ElsProjects> queryWrapper = Condition.getQueryWrapper(projects, ElsProjects.class);
        Long baseRole = AuthUtil.getBaseRole();
        List<ScienceProjectsExcel> list = null;
        //专家导出自己可以评分的项目
        if(BaseRoleUtil.hasRole(baseRole,BaseRoleConstant.BASE_EXPERT_ROLE)) {
            list = elsProjectsService.exportScienceProjects(queryWrapper, projectType, AuthUtil.getUserId());
        }else{
            list = elsProjectsService.exportScienceProjects(queryWrapper, projectType, null);
        }
        ExcelUtil.export(response, "材料评审项目数据" + DateUtil.time(), "材料评审项目数据表", list, ScienceProjectsExcel.class);
    }
    /**
     * 导出职工培训项目模板
     */
    @GetMapping("export-template-workers")
    @ApiOperation(value = "导出职工培训项目模板")
    public void exportWorkersTemplate(HttpServletResponse response) {
        List<WorkersProjectsExcel> list = new ArrayList<>();
        ExcelUtil.export(response, "职工培训项目数据模板", "职工培训项目数据表", list, WorkersProjectsExcel.class);
    }
    /**
     * 导出人才评价培训项目模板
     */
    @GetMapping("export-template-personnel")
    @ApiOperation(value = "导出人才评价培训项目模板")
    public void exportPersonnelTemplate(HttpServletResponse response) {
        List<PersonnelProjectsExcel> list = new ArrayList<>();
        ExcelUtil.export(response, "人才评价培训项目数据模板", "人才评价培训项目数据表", list, PersonnelProjectsExcel.class);
    }
    /**
     * 导出培训开发项目模板
     */
    @GetMapping("export-template-exploit")
    @ApiOperation(value = "导出培训开发项目模板")
    public void exportExploitTemplate(HttpServletResponse response) {
        List<ExploitProjectsExcel> list = new ArrayList<>();
        ExcelUtil.export(response, "培训开发项目数据模板", "培训开发项目数据表", list, ExploitProjectsExcel.class);
    }
    /**
     * 导出培训购置项目模板
     */
    @GetMapping("export-template-purchase")
    @ApiOperation(value = "导出培训购置项目模板")
    public void exportPurchaseTemplate(HttpServletResponse response) {
        List<PurchaseProjectsExcel> list = new ArrayList<>();
        ExcelUtil.export(response, "培训购置项目数据模板", "培训购置项目数据表", list, PurchaseProjectsExcel.class);
    }
    /**
     * 导出生产辅助技改(大修)项目模板
     */
    @GetMapping("export-template-produce")
    @ApiOperation(value = "导出生产辅助技改(大修)项目模板")
    public void exportProduceTemplate(HttpServletResponse response) {
        List<ProduceProjectsExcel> list = new ArrayList<>();
        ExcelUtil.export(response, "生产辅助技改(大修)项目数据模板", "生产辅助技改(大修)项目数据表", list, ProduceProjectsExcel.class);
    }
    /**
     * 导出材料评审模板
     */
    @GetMapping("export-template-science")
    @ApiOperation(value="导出材料评审模板")
    public void exportTemplateScience(HttpServletResponse response){
        List<ProduceProjectsExcel> list = new ArrayList<>();
        ExcelUtil.export(response, "材料评审数据模板", "材料评审数据表", list, ProduceProjectsExcel.class);
    }
}